<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="配方编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入配方编码"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="配方号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="no">
              <a-input v-model="model.no" placeholder="请输入配方号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="配方名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入配方名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="配方类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="category">
              <j-dict-select-tag type="list" v-model="model.category" dictCode="pf_category" placeholder="请选择配方类别"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="配方类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <j-dict-select-tag type="list" v-model="model.type" dictCode="pf_type" placeholder="请选择配方类型"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="年" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
<!--              <a-date-picker ref="datePicker" placeholder="请选择年"-->
<!--                      v-model="model.year"-->
<!--                      pickerType="year"-->
<!--                      dateFormat="yyyy"-->
<!--                      :open="datePickerOpen"-->
<!--                      @panelChange="onDatePickerChange"-->
<!--                      @openChange="onDatePickerOpenChange"-->
<!--                      style="width: 100%"/>-->
              <a-date-picker ref="datePicker" placeholder="请选择年"
                             v-model="model.year"
                             mode="year"
                             value-format="YYYY"
                             format='YYYY'
                             :open="datePickerOpen"
                             @panelChange="onDatePickerChange"
                             @openChange="onDatePickerOpenChange"
                             style="width: 100%"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <!-- 新增 -->
          <a-col :span="24">
            <a-button
              type="primary"
              icon=""
              size="large"
              @click="addMaterielFormula">
              新增配方明细
            </a-button>
            <erp-goods-list-model ref="selectGoodsList"
                                  :modalWidth="modalWidth"
                                  :category="category"
                                  @goodsOk="goodsOk"
                                  checkval='checkbox'>
            </erp-goods-list-model>
          </a-col>
          <a-col :span="24">
            <!-- 表格 -->
            <a-table bordered :data-source="model.detailList"
                     tableLayout='fixed'
                     :columns="materielColumns"
                     :rowKey="record=>record.detailNo"
                     :pagination="false">
<!--              <template slot="formula" slot-scope="text, record">-->
<!--                <editable-cell :text="text" @change="onCellChange(record.key, 'name', $event)" />-->
<!--              </template>-->
              <template slot="formula" slot-scope="text, record">
                <editable-cell :text="text" @change="onCellChange(record, 'formula', $event)" ></editable-cell>
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                  title="确认删除?"
                  @confirm="() => onDelete(record.materielId)"
                >
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
<!--                <a @click="handleEdit(record)">保存</a>-->
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import {httpAction, postAction,getAction,deleteAction} from '@/api/manage'
import ErpGoodsListModel from "@comp/base/modal/ErpGoodsListModal";
import EditableCell from '@comp/table/EditableCell'
import Moment from 'moment'


export default {
  name: 'ErpGoodsFormulaForm',
  components: {ErpGoodsListModel,EditableCell},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      datePickerOpen: false,
      model: {
        code: '',
        category: 1,
        detailList:[],
        year: ''
      },
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      confirmLoading: false,
      category: '4',
      modalWidth: 1250,
      materielColumns: [
        {
          title: '编号',
          dataIndex: 'detailNo',
        },
        {
          title: '物料名称',
          dataIndex: 'materielName',
        },
        {
          title: '规格',
          dataIndex: 'spec',
        },
        {
          title: '是否客户自带料',
          dataIndex: 'isClientOwn',
        },
        {
          title: '配方%',
          dataIndex: 'formula',
          scopedSlots: { customRender: 'formula' },
          width: 150,
        },
        {
          title: '实际数量',
          dataIndex: 'actualQuantity',
        },
        {
          title: '配方公式',
          dataIndex: 'computingFormula',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      validatorRules: {
        code: [
          {required: true, message: '请输入配方编码!'},
        ],
        no: [
          {required: true, message: '请输入配方号!'},
        ],
        name: [
          {required: true, message: '请输入配方名称!'},
        ],
        category: [
          {required: true, message: '请输入配方类别!'},
        ],
        type: [
          {required: true, message: '请输入配方类型!'},
        ],
        year: [
          {required: true, message: '请输入年!'},
        ],
      },
      url: {
        add: "/base/erpGoodsFormula/add",
        edit: "/base/erpGoodsFormula/edit",
        queryById: "/base/erpGoodsFormula/queryById"
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    onCellChange(record, dataIndex, value) {
      const dataSource = [...this.model.detailList];
      const target = dataSource.find(item => item.detailNo === record.detailNo);
      // console.log(target,key,dataIndex,value)
      if (record) {
        target[dataIndex] = value;
        this.model.detailList = dataSource;
        postAction('/base/erpGoodsFormulaDetail/compute/formula',
          {list:this.model.detailList,detail: record }).then(res => {
          if(res.success){
            this.$set(record, "actualQuantity", res.result)
            console.log('计算完的值', this.model.detailList)
          }
        })
      }
    },
    onDelete(key){
      console.log(key)
      const dataSource = [...this.model.detailList];
      this.model.detailList = dataSource.filter(item => item.materielId != key);
      // deleteAction('base/erpGoodsFormulaDetail/delete',{id:key}).then(res=>{
      //   if(res.success){
      //
      //   }
      // })

    },
    goodsOk: function(datas) {
      // this.handleAdd();
      let _this = this;
      let ids = datas.map(item => item.id);
      postAction('/base/erpGoods/list/ids', { ids: ids }).then(res => {
        let erpGoodsList = res.result;
        erpGoodsList.forEach(function(item,index){
          debugger
          let detail = {};
          detail.detailNo = item.code;
          detail.materielName = item.name;
          detail.spec = item.noneSpec;
          detail.isClientOwn = item.isPublic;
          detail.materielId = item.id;
          _this.filterMaterielId(item.id);
          _this.model.detailList.push(detail);
          //配方公式
          getAction('/base/erpGoodsFormulaGs/query', { materialId: item.id }).then(res => {
            if(res.result && res.result.length>0){
              // _this.model.detailList[_this.model.detailList.length - 1].computingFormula = res.result[0].gs;
              _this.model.detailList[_this.model.detailList.length - 1].gsMaterialId = res.result[0].gsMaterialId;
              _this.$set(_this.model.detailList[_this.model.detailList.length - 1], "computingFormula", res.result[0].gs)
            }
          })
        })
      })
    },
    filterMaterielId(materielId){
      if(this.model.detailList && this.model.detailList.length > 0){
        this.model.detailList = this.model.detailList.filter(function(item) {
          return item.materielId !== materielId;
        });
      }
    },
    addMaterielFormula: function(){
      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(()=>{
        this.$refs.selectGoodsList.add();
      })
      // this.$refs.selectGoodsList.add();
      // this.$refs.selectGoodsList.title = "新增";
      // this.$refs.selectGoodsList.disableSubmit = false;
    },
    onDatePickerOpenChange(status) {
      console.log("dalkia")
      this.datePickerOpen = true;
    },
    onDatePickerChange: function(dateText) {
      this.datePickerOpen = false
      let date = dateText._d;
      console.log('riqi', Moment(date).format("YYYY"))
      this.model.year=date&& Moment(date).locale('en').format("YYYY");

    },
    getFormulaCode() {
      postAction('/sys/fillRule/executeRuleByCode/cppf', {}).then(res => {
        this.model.code = res.result;
      })
    },
    add() {
      this.edit(this.modelDefault);
      this.getFormulaCode();
    },
    edit(record) {
      this.model = Object.assign({}, record);
      if(this.model.id)
      getAction('/base/erpGoodsFormulaDetail/list', {formulaCode:this.model.id}).then(res => {
        this.model.detailList = res.result;
      })
      this.visible = true;
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
  }
}
</script>
